package com.iss.apartmentmanage.config.security;

import com.alibaba.fastjson.JSON;
import com.iss.apartmentmanage.config.menu.MenuTree;
import com.iss.apartmentmanage.config.menu.MenuTreeUtils;
import com.iss.apartmentmanage.entity.Menu;
import com.iss.apartmentmanage.entity.User;
import com.iss.apartmentmanage.mapper.MenuMapper;
import com.iss.apartmentmanage.model.MyResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Component
public class SelfAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    MenuMapper menuMapper;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        logger.info("登陆成功");
        MyResponseData responseBody = new MyResponseData();

        String username=authentication.getName();
        List<Menu> menuList = menuMapper.selectMenuByUserId(username);

        Map<String,Object> data = new HashMap<>();
        data.put("menuTree", MenuTreeUtils.generateMenuTree(menuList));
        responseBody.setStatus("201");
        responseBody.setMsg("成功");
        responseBody.setErrorCode(1);
        responseBody.put("data",data);

        //跨域的设置
        httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods","*");
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //把值塞到response里面返回给前台
        httpServletResponse.getWriter().write(JSON.toJSONString(responseBody));

//        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
//        if (roles.contains("ROLE_Admin")) {
//            response.sendRedirect("/admin/home.html");
//        }
















    }
}
